<?php
if(!defined("DNREAD")) exit();

class userapi{
    var $db;
    var $data =
    array(
    'prefix' => 'phpbb_',
    'table' => '',
    'userid' => 'user_id',
    'forumpath' => '/forum/',
    'avatarpath' => '/forum/images/avatars/upload/',
    'avatargalpath' => '/forum/images/avatars/gallery/',
    'setting'=>array(),
    'linkreg' => 'forum/ucp.php?mode=register',
    'linklost' => 'forum/ucp.php?mode=sendpassword',
    'linkprivmess' => 'forum/ucp.php?i=pm&amp;folder=inbox',
    'linksendmess' => '/forum/ucp.php?i=pm&amp;mode=compose&amp;u=',
    'linkprofile' => '/forum/memberlist.php?mode=viewprofile&amp;u='
    );
    var $set =
    array(
    'prefix' => 'all_prefix',
    'forumpath' => 'all_path',
    'avatarpath' => 'avatar_path',
    'avatargalpath' => 'avatar_galpath',
    'linkreg' => 'registr',
    'linklost' => 'rest_pass',
    'linkprivmess' => 'private_message',
    'linksendmess' => 'link_send_mess',
    'linkprofile' => 'your_profile'
    );
    var $usermain =
    array(
    'logged' => 0,
    'userid' => 0,
    'gid' => 0,
    'uname' => '',
    'umail' => '',
    'regdate' => '',
    'lastvisit' => '',
    'icq' => '',
    'msn' => '',
    'www' => '',
    'newmsg' => 0,
    'newmsgnr' => 0,
    'avatar' => ''
    );
    var $userfilter =
    array(
    'login' => array('username','login','input'),
    'register' => array('user_regdate','registr_date','date'),
    'visit' => array('user_lastvisit','last_visit','date'),
    'email' => array('user_email','E-Mail','input'),
    );
    var $groups =
    array();

    function userapi(&$db,$logged = false)
    {
        global $setting,$conf,$group;
        $this->db = &$db;
        if (isset($setting['datainteg']) && !empty($setting['datainteg']) || isset($conf['datainteg']) && !empty($conf['datainteg'])) {
             $data = (isset($conf['datainteg']) && !empty($conf['datainteg'])) ? @unserialize($conf['datainteg']) : @unserialize($setting['datainteg']);
             $n = '';
             foreach ($this->data as $k => $v) {
             	$n[$k] = (isset($data[$k])) ? $data[$k] : $v;
             }
             if(is_array($n)){
                 $this->data = $n;
             }
        }
        if (is_array($group)) {
            foreach ($group as $k => $v){
                if ($v['fid'] > 0) {
                    $this->groups[$v['fid']] = array('gid'=>$v['gid'],'title'=>$v['title']);
                }
           }
        }
        $this->data['table'] = $this->data['prefix'].'users WHERE user_id > 1 AND user_type <> 2';
        if ($logged) {
            $sinq = $this->db->query("SELECT config_name,config_value FROM ".$this->data['prefix']."config WHERE config_name IN ('browser_check','cookie_domain','cookie_name','forwarded_for_check','ip_check','session_length')");
            while ($sitem = $this->db->fetchrow($sinq)) {
                $this->data['setting'][$sitem['config_name']] = $sitem['config_value'];
            }
            return $this->userarray();
        }
    }

    function short_ipv6($ip, $length)
    {
        if($length < 1) return '';
            $blocks = substr_count($ip, ':') + 1;
        if ($blocks < 9) {
                $ip = str_replace('::', ':' . str_repeat('0000:', 9 - $blocks), $ip);
        }
        if ($ip[0] == ':') {
            $ip = '0000' . $ip;
        }
        if ($length < 4) {
            $ip = implode(':', array_slice(explode(':', $ip), 0, 1 + $length));
        }
        return $ip;
    }

    function avatar($type, $scr, $link = false)
    {
        $avatar = '';
        if ($scr) {
            if ($type == 1) {
                $avatar = ($link) ? '<img src="'.$this->data['forumpath'].'download/file.php?avatar='.$scr.'">' : $this->data['forumpath'].'download/file.php?avatar='.$scr;
            }
            if ($type == 2) {
                $avatar = ($link) ? '<img src="'.$scr.'">' : $scr;
            }
            if ($type == 3) {
                $avatar = ($link) ? '<img src="'.$this->data['avatarpath'].$this->data['avatargalpath'].$scr.'">' : $this->data['avatarpath'].$this->data['avatargalpath'].$scr;
            }
        }
        return $avatar;
    }

    function userarray()
    {
        global $group;
        $this->ua['session'] = isset($_COOKIE[$this->data['setting']['cookie_name'].'_sid']) ? stripslashes($_COOKIE[$this->data['setting']['cookie_name'].'_sid']) : '';
        if(!preg_match('/^[A-Za-z0-9]*$/',$this->ua['session'])){ return; }
        $this->ua['userid'] = isset($_COOKIE[$this->data['setting']['cookie_name'].'_u']) ? intval($_COOKIE[$this->data['setting']['cookie_name'].'_u']) : '';
        $this->ua['browser'] = (!empty($_SERVER['HTTP_USER_AGENT'])) ? substr(htmlspecialchars($_SERVER['HTTP_USER_AGENT']), 0, 149) : '';
        $this->ua['forward'] = (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) ? (string) $_SERVER['HTTP_X_FORWARDED_FOR'] : '';
        if ($this->data['setting']['forwarded_for_check']) {
            $this->ua['forward'] = preg_replace('#, +#', ', ', $this->ua['forward']);
            $ipv4 = '#^(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$#';
            $ipv6 = '#^(?:(?:(?:[\dA-F]{1,4}:){6}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:::(?:[\dA-F]{1,4}:){5}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:):(?:[\dA-F]{1,4}:){4}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,2}:(?:[\dA-F]{1,4}:){3}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,3}:(?:[\dA-F]{1,4}:){2}(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,4}:(?:[\dA-F]{1,4}:)(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,5}:(?:[\dA-F]{1,4}:[\dA-F]{1,4}|(?:(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.){3}(?:\d{1,2}|1\d\d|2[0-4]\d|25[0-5])))|(?:(?:[\dA-F]{1,4}:){1,6}:[\dA-F]{1,4})|(?:(?:[\dA-F]{1,4}:){1,7}:))$#i';
            $ips = explode(', ', $this->ua['forward']);
            foreach ($ips as $ip) {
                if(!empty($ip) && !preg_match($ipv4, $ip) && !preg_match($ipv6, $ip)){
                    $this->ua['forward'] = '';
                    break;
                }
            }
        }
        $this->ua['ip'] = htmlspecialchars((!empty($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : ((!empty($_ENV['REMOTE_ADDR'])) ? $_ENV['REMOTE_ADDR'] : getenv('REMOTE_ADDR')));
        if (!empty($this->ua['session']) && $this->ua['userid'] > 1) {
            $new = $this->db->fetchrow($this->db->query("SELECT u.user_id,s.* FROM ".$this->data['prefix']."sessions s, ".$this->data['prefix']."users u
                                                WHERE session_id = '".$this->db->escape(trim($this->ua['session']))."'
                                                AND s.session_ip = '".$this->db->escape($this->ua['ip'])."'
                                                AND s.session_time > ".(int)(NEWTIME - $this->data['setting']['session_length'])."
                                                AND u.user_id = s.session_user_id"));
            if (isset($new['user_id'])) {
                if (strpos($this->ua['ip'],':') !== false && strpos($new['session_ip'], ':') !== false) {
                    $s_ip = short_ipv6($new['session_ip'], $this->data['setting']['ip_check']);
                    $u_ip = short_ipv6($this->ua['ip'], $this->data['setting']['ip_check']);
                } else {
                    $s_ip = implode('.', array_slice(explode('.', $new['session_ip']), 0, $this->data['setting']['ip_check']));
                    $u_ip = implode('.', array_slice(explode('.', $this->ua['ip']), 0, $this->data['setting']['ip_check']));
                }
                $s_browser = ($this->data['setting']['browser_check']) ? strtolower(substr($new['session_browser'], 0, 149)) : '';
                $u_browser = ($this->data['setting']['browser_check']) ? strtolower(substr($this->ua['browser'], 0, 149)) : '';
                $s_forwarded_for = ($this->data['setting']['forwarded_for_check']) ? substr($new['session_forwarded_for'], 0, 254) : '';
                $u_forwarded_for = ($this->data['setting']['forwarded_for_check']) ? substr($this->ua['forward'], 0, 254) : '';
                if ($u_ip === $s_ip && $s_browser === $u_browser && $s_forwarded_for === $u_forwarded_for) {
                    $newuser = $this->db->fetchrow($this->db->query("SELECT u.*,b.ban_id FROM ".$this->data['prefix']."users u
                                                      LEFT JOIN ".$this->data['prefix']."banlist b ON b.ban_userid = u.user_id
                                                      WHERE user_id = '".intval($new['user_id'])."' LIMIT 1"));
                    if (intval($newuser['ban_id']) == 0 && intval($newuser['user_id']) > 1) {
                        $gid = (isset($this->groups[$newuser['group_id']]['gid']) && intval($this->groups[$newuser['group_id']]['gid']) > 0) ? $this->groups[$newuser['group_id']]['gid'] : 0;
                        $this->usermain = array(
                        'logged'=>1,
                        'userid'=>intval($newuser['user_id']),
                        'gid'=>$gid,
                        'uname'=>$newuser['username'],
                        'umail'=>$newuser['user_email'],
                        'regdate'=>$newuser['user_regdate'],
                        'lastvisit'=>$newuser['user_lastvisit'],
                        'icq'=>$newuser['user_icq'],
                        'msn'=>$newuser['user_msnm'],
                        'www'=>$newuser['user_website'],
                        'newmsg'=>intval($newuser['user_new_privmsg']),
                        'newmsgnr'=>intval($newuser['user_unread_privmsg']),
                        'avatar'=>$this->avatar(intval($newuser['user_avatar_type']),$newuser['user_avatar'],true)
                        );
                    }
                }
            }
        }
    }

    function logout()
    {
        if ($this->usermain['logged'] == 1 && intval($this->usermain['userid']) > 0) {
            @setcookie($this->data['cookie'].'_data', '', 1);
            @setcookie($this->data['cookie'].'_sid', '', 0);
            $this->db->query("UPDATE ".$this->data['prefix']."users SET user_lastvisit = ".NEWTIME." WHERE user_id = '".$this->usermain['userid']."'");
            $this->db->query("DELETE FROM ".$this->data['prefix']."sessions_keys WHERE user_id = '".$this->usermain['userid']."'");
            $this->db->query("DELETE FROM ".$this->data['prefix']."sessions WHERE session_user_id = '".$this->usermain['userid']."'");
        }
    }

    function checkpwd($passw)
    {
        return (strlen($passw) > 32) ? 0 : 1;
    }

    function checklogin($login)
    {
        return (strlen($login) > 32 || strlen($login) < 3) ? 0 : 1;
    }

    function issetmail($mail)
    {
        return $this->db->numrows($this->db->query("SELECT user_id FROM ".$this->data['prefix']."users WHERE user_email='".$this->db->escape($mail)."' AND user_id <> ".$this->usermain['userid'].""));
    }

    function addmail($mail)
    {
        $this->db->query("UPDATE ".$this->data['prefix']."users SET user_email = '".$this->db->escape($mail)."' WHERE user_id = ".$this->usermain['userid']."");
    }

    function addurl($url)
    {
        if ($url) {
            $url = (!preg_match('#^http[s]?:\/\/#i',$url)) ? "http://".$url : $url;
            $url = (!preg_match('#^http[s]?\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i',$url)) ? '' : $url;
        } else {
            $url = '';
        }
        return $url;
    }

    function adduse($icq, $www, $msn)
    {
        $this->db->query("UPDATE ".$this->data['prefix']."users SET user_icq = '".$this->db->escape($icq)."', user_website='".$this->db->escape($www)."',user_msnm = '".$this->db->escape($msn)."' WHERE user_id = '".intval($this->usermain['userid'])."'");
    }

    function associat($in = false)
    {
        $associat = array();
        if ($in) {
            $inq = $this->db->query("SELECT user_id,username,user_regdate,user_avatar,user_avatar_type,user_icq,user_website FROM ".$this->data['prefix']."users WHERE user_id IN (".$this->db->escape($in).")");
            while ($item = $this->db->fetchrow($inq)) {
                $associat[$item['user_id']] = array(
                'userid' => $item['user_id'],
                'uname' => $item['username'],
                'regdate' => $item['user_regdate'],
                'avatar' => $this->avatar(intval($item['user_avatar_type']),$item['user_avatar'],false),
                'icq' => $item['user_icq'],
                'www' => $item['user_website']
                );
            }
        }
        return $associat;
    }

    function login($login, $pass)
    {
        if ($this->usermain['logged'] == 0 && intval($this->usermain['userid']) == 0) {
            $newuser = $this->db->fetchrow($this->db->query("SELECT u.*,b.ban_id FROM ".$this->data['prefix']."users u
                                                    LEFT JOIN ".$this->data['prefix']."banlist b ON b.ban_userid = u.user_id
                                                    WHERE u.username = '".$this->db->escape($login)."'"));
            if (intval($newuser['ban_id']) > 0) {
                define('THIS_BANNED',1);
            }
            if (intval($newuser['user_id']) > 1 && intval($newuser['ban_id']) == 0) {
                if ($this->phpbb_check_hash($pass,$newuser['user_password'])) {
                    $this->ua['sessionhash'] = md5(uniqid($this->ua['ip']));
                    $this->ua['forward'] = substr($this->ua['forward'],0,254);
                    $this->db->query("REPLACE INTO ".$this->data['prefix']."sessions (
                          session_id,
                          session_user_id,
                          session_last_visit,
                          session_start,
                          session_time,
                          session_ip,
                          session_browser,
                          session_forwarded_for,
                          session_page,
                          session_viewonline,
                          session_autologin,
                          session_admin
                          ) VALUES (
                          '".$this->db->escape($this->ua['sessionhash'])."',
                          '".intval($newuser['user_id'])."',
                          '".NEWTIME."',
                          '".NEWTIME."',
                          '".NEWTIME."',
                          '".$this->db->escape($this->ua['ip'])."',
                          '".$this->db->escape($this->ua['browser'])."',
                          '".$this->db->escape($this->ua['forward'])."', '', 0, 0, 0)");
                    @setcookie($this->data['setting']['cookie_name'].'_u',$newuser['user_id'],NEWTIME + 31536000,'/',$this->data['setting']['cookie_domain'],0);
                    @setcookie($this->data['setting']['cookie_name'].'_k','',NEWTIME + 31536000,'/',$this->data['setting']['cookie_domain'],0);
                    @setcookie($this->data['setting']['cookie_name'].'_sid',$this->ua['sessionhash'],NEWTIME + 31536000,'/',$this->data['setting']['cookie_domain'],0);
                    $gid = (isset($this->groups[$newuser['group_id']]['gid']) && intval($this->groups[$newuser['group_id']]['gid']) > 0) ? $this->groups[$newuser['group_id']]['gid'] : 0;
                    $this->usermain = array(
                    'logged'=>1,
                    'userid'=>intval($newuser['user_id']),
                    'gid'=>$gid,
                    'uname'=>$newuser['username'],
                    'umail'=>$newuser['user_email'],
                    'regdate'=>$newuser['user_regdate'],
                    'lastvisit'=>$newuser['user_lastvisit'],
                    'icq'=>$newuser['user_icq'],
                    'msn'=>$newuser['user_msnm'],
                    'www'=>$newuser['user_website'],
                    'newmsg'=>intval($newuser['user_new_privmsg']),
                    'newmsgnr'=>intval($newuser['user_unread_privmsg']),
                    'avatar'=>$this->avatar(intval($newuser['user_avatar_type']),$newuser['user_avatar'],true)
                    );
                }
            }
        }
    }

    function group()
    {
        $associat = array();
        $inq = $this->db->query("SELECT * FROM ".$this->data['prefix']."groups");
        while ($item = $this->db->fetchrow($inq)) {
            $associat[$item['group_id']] = $item['group_name'];
        }
        return $associat;
    }

    function userlist($sf, $nu, $p, $sess, $sql)
    {
        global $lang;
        $inq = $this->db->query("SELECT u.*,b.ban_id FROM ".$this->data['prefix']."users AS u LEFT JOIN ".$this->data['prefix']."banlist AS b ON b.ban_userid = u.user_id WHERE u.user_id > 1 AND u.user_type <> 2".$sql." ORDER BY u.user_id DESC LIMIT $sf,$nu");
        while ($item = $this->db->fetchrow($inq)) {
            $style = (intval($item['ban_id']) > 0) ? 'noactive' : 'work-lite';
            echo '<tr>'
                 .'<td class="'.$style.' center">'
                 .$item['username']
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .format_time($item['user_regdate'],0)
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .format_time($item['user_lastvisit'],1)
                 .'</td>'
                 .'<td class="'.$style.' center">'
                 .'<a href=mailto:'.$item['user_email'].'>'.$item['user_email'].'</a>'
                 .'</td>'
                 .'<td class="'.$style.' center">';
            if ($item['user_id'] > 1) {
                 //if (intval($item['ban_id']) > 0) {
                 //    echo '<a href="user.php?dn=unban&uid='.$item['user_id'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['ban_del'].'" src="template/'.$sess['skin'].'/images/unblock.gif" border="0"></a>';
                 //} else {
                 //    echo '<a href="user.php?dn=ban&uid='.$item['user_id'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['ban_add'].'" src="template/'.$sess['skin'].'/images/block.gif"></a>'
                 echo '<a href="user.php?dn=edit&uid='.$item['user_id'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['all_edit'].'" src="template/'.$sess['skin'].'/images/edit.gif"></a>';
                 //       .'<a href="user.php?dn=del&uid='.$item['user_id'].'&p='.$p.'&nu='.$nu.'&ops='.$sess['hash'].'"><img alt="'.$lang['all_delet'].'" src="template/'.$sess['skin'].'/images/del.gif"></a>';
                 //}
            }
            echo '</td>'
                 .'</tr>';
        }
    }

   function userdel($uid)
   {
      //if($uid > 2){
      //    $this->db->query("DELETE FROM ".$this->data['prefix']."users WHERE user_id='$uid'");
      //}
   }

   function bandel($uid)
   {
       //if ($uid > 0) {
       //    $this->db->query("DELETE FROM ".$this->data['prefix']."banlist WHERE ban_userid='$uid'");
       //}
   }

   function banadd($uid)
   {
       //if ($uid > 0) {
       //    if ($this->db->numrows($this->db->query("SELECT ban_id FROM ".$this->data['prefix']."banlist WHERE ban_userid='$uid'")) == 0) {
       //        $this->db->query("INSERT INTO ".$this->data['prefix']."banlist VALUES (NULL,$uid,'',NULL)");
       //    }
       //}
   }

   function useredit($uid)
   {
       global $lang;
       if ($uid > 0) {
           $item = $this->db->fetchrow($this->db->query("SELECT * FROM ".$this->data['prefix']."users WHERE user_id = '".$uid."'"));
           echo '<table  cellpadding="1" cellspacing="1" class="work">'
                .'<tr><td class="work-title center" colspan="2">'.$lang['edit_user'].' : '.$item['username'].'</td></tr>'
                .'<tr>'
                .'<td class="work-clip strong center" width="20%">E-Mail :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[mail]" size="50" maxlength="50" type="text" value="'.$item['user_email'].'"> '
                .'</td>'
                .'<tr>'
                .'<td class="work-clip strong center" width="20%">'
                .'ICQ :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[icq]" size="50" maxlength="15" type="text" value="'.$item['user_icq'].'"> '
                .'</td>'
                .'</tr>'
                .'<tr>'
                .'<td class="work-clip strong center" width="20%">'
                .'MSN :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[msn]" size="50" maxlength="50" type="text" value="'.$item['user_msnm'].'"> '
                .'</td>'
                .'</tr>'
                .'<tr>'
                .'<td class="work-clip strong center" width="20%">'
                .'URL :'
                .'</td>'
                .'<td class="work-lite" width="80%">'
                .'<input name="edit[www]" size="50" maxlength="50" type="text" value="'.$item['user_website'].'"> '
                .'</td>'
                .'</tr>';
       }
   }

   function usersave($uid, $edit)
   {
       if ($uid > 0 && is_array($edit)) {
           if (isset($edit['mail']) && !empty($edit['mail']) && $this->db->numrows($this->db->query("SELECT user_id FROM ".$this->data['prefix']."users WHERE user_email = '".$this->db->escape($edit['mail'])."' AND user_id <> $uid")) == 0) {
               $this->db->query("UPDATE ".$this->data['prefix']."users SET user_email = '".$this->db->escape($edit['mail'])."' WHERE user_id = '$uid'");
           }
           if (isset($edit['icq'])) {
               $edit['icq'] = preg_match('/^[0-9]+$/D',$edit['icq']) ? $edit['icq'] : '';
               $this->db->query("UPDATE ".$this->data['prefix']."users SET user_icq = '".$this->db->escape($edit['icq'])."' WHERE user_id = '$uid'");
           }
           if (isset($edit['www'])) {
               $edit['www'] = preg_match('/^[http]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i',$edit['www']) ? $edit['www'] : '';
               $this->db->query("UPDATE ".$this->data['prefix']."users SET user_website = '".$this->db->escape($edit['www'])."' WHERE user_id = '$uid'");
           }
           if (isset($edit['msn'])) {
              $edit['msn'] = preg_match('/^[A-Za-z0-9_\.\-]+@+[A-Za-z0-9_\w\.\-]+\.+[A-Za-z]{2,4}+$/i',$edit['msn']) ? $edit['msn'] : '';
              $this->db->query("UPDATE ".$this->data['prefix']."users SET user_msnm = '".$this->db->escape($edit['msn'])."' WHERE user_id = '$uid'");
           }
       }
   }

  function phpbb_check_hash($password, $hash)
  {
      $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
      if (strlen($hash) == 34) {
          return ($this->_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false;
      }
      return (md5($password) === $hash) ? true : false;
  }

  function _hash_encode64($input, $count, &$itoa64)
  {
      $output = '';
      $i = 0;
      do
      {
          $value = ord($input[$i++]);
          $output .= $itoa64[$value & 0x3f];
          if($i < $count){ $value |= ord($input[$i]) << 8; }
          $output .= $itoa64[($value >> 6) & 0x3f];
          if($i++ >= $count){  break; }
          if($i < $count){ $value |= ord($input[$i]) << 16; }
          $output .= $itoa64[($value >> 12) & 0x3f];
          if($i++ >= $count){ break;}
          $output .= $itoa64[($value >> 18) & 0x3f];
      }
      while ($i < $count);
      return $output;
  }

  function _hash_crypt_private($password, $setting, &$itoa64)
  {
      $output = '*';
      if(substr($setting, 0, 3) != '$H$'){ return $output; }
      $count_log2 = strpos($itoa64, $setting[3]);
      if($count_log2 < 7 || $count_log2 > 30){ return $output; }
      $count = 1 << $count_log2;
      $salt = substr($setting, 4, 8);
      if(strlen($salt) != 8){ return $output; }
      if (PHP_VERSION >= 5) {
          $hash = md5($salt.$password,true);
          do
          {
              $hash = md5($hash.$password,true);
          }
          while (--$count);
      } else {
          $hash = pack('H*',md5($salt.$password));
          do
          {
              $hash = pack('H*', md5($hash . $password));
          }
         while (--$count);
      }
      $output = substr($setting, 0, 12);
      $output .= $this->_hash_encode64($hash, 16, $itoa64);
      return $output;
  }

  function messagelast($bs)
  {
      global $api,$lang;
      $inq = $this->db->query("SELECT forum_id,forum_password FROM ".$this->data['prefix']."forums");
      $qe = $re = '';
      $ignore = array();
      while ($item = $this->db->fetchrow($inq)) {
          if ($item['forum_password'] != '') {          	$ignore[] = $item['forum_id'];
          }
      }
      if (count($ignore) > 0) {
          $qe = " AND forum_id NOT IN (".implode(',',$ignore).") ";
      }
      $bs['order'] = (isset($bs['order']) && $bs['order'] == 'desc') ? 'desc' : 'asc';
      $inq = $this->db->query("SELECT * FROM ".$this->data['prefix']."topics WHERE topic_approved != 0
      AND topic_approved = 1 AND (topic_moved_id = 0 OR topic_moved_id = '')
      ".$qe."ORDER BY topic_last_post_id ".$bs['order']." LIMIT 0,".$bs['col']);
      if ($this->db->numrows($inq) > 0) {
          $target = (empty($bs['target'])) ? '' : ' target="'.$bs['target'].'"';
          $re.= '<table class="forum" width="100%" cellspacing="0" cellpadding="0">'
                .'<tbody class="forumbody">'
                .'<tr>'
                .'<td class="forumtitle">'.$lang['subject'].'</td>';
          if ($bs['author'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['author'].'</td>';
          }
          if ($bs['date'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['all_data'].'</td>';
          }
          if ($bs['replie'] == 'yes') {
              $re.= '<td class="forumtitle">'.$lang['comment_total'].'</td>';
          }
          $re.= '</tr>'
                .'</tbody>';
          while ($item = $this->db->fetchrow($inq)) {
              $title = (strlen($item['topic_title']) > 55) ? substr($item['topic_title'],0,55)."..." : $item['topic_title'];
              $topid = $item['topic_id'];
              $forid = $item['forum_id'];
              $lasid = $item['topic_last_post_id'];
              $poster = $item['topic_last_poster_name'];
              $re.= '<tr>'
                    .'<td class="forumtopic">'
                    .'<a href="forum/viewtopic.php?f='.$forid.'&t='.$topid.'" title="'.$title.'"'.$target.'>'.$title.'</a>'
                    .'</td>';
              if ($bs['author'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                        .'<a href="forum/viewtopic.php?f='.$forid.'&t='.$topid.'&p='.$lasid.'#p'.$lasid.'"'.$target.'>'.$poster.'</a>'
                        .'</td>';
              }
              if ($bs['date'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                        .'<span class="time">'.$api->sitetime($item['topic_last_post_time']).'</span>'
                        .'</td>';
              }
              if ($bs['replie'] == 'yes') {
                  $re.= '<td class="forumtopic">'
                    .'<span class="time">'.$item['topic_replies'].'</span>'
                    .'</td>';
              }
              $re.= '</tr>';
          }
          $re.= '</table>';
      }
      return $re;
  }
}
?>